# a.py
from Crypto import Random
from Crypto.Cipher import PKCS1_v1_5 as Cipher_pkcs1_v1_5
from Crypto.PublicKey import RSA
import base64
import os

#生成密钥
def write_pwd(int):
    random_generator = Random.new().read
    rsa = RSA.generate(int, random_generator)
    try:
        # 生成私钥
        private_key = rsa.exportKey()
        with open('private.pem', 'w') as f:
            f.write(private_key.decode('utf-8'))
        # 生成公钥
        public_key = rsa.publickey().exportKey()
        with open('public.pem', 'w') as f:
            f.write(public_key.decode('utf-8'))
        return  private_key,public_key
    except:
        return False

#加密函数，传入需要加密的文本，返回加密后的明文
def rsa_encrypt(plaintext):

    base_dir = os.path.dirname(__file__)
    config_path = os.path.join(base_dir, 'public.pem')
    rsakey = RSA.importKey(open(config_path).read())
    cipher = Cipher_pkcs1_v1_5.new(rsakey)  # 创建用于执行pkcs1_v1_5加密或解密的密码
    cipher_text = base64.b64encode(cipher.encrypt(plaintext.encode('utf-8')))
    p = cipher_text.decode('utf-8')
    return p

#解密函数，返回解密后的明文
def rsa_decrypt(ciphertext, priv_key):

    rsakey = RSA.importKey(priv_key)  # 导入私钥
    cipher = Cipher_pkcs1_v1_5.new(rsakey)
    text = cipher.decrypt(base64.b64decode(ciphertext), None)
    p = text.decode('utf8')
    return p

#测试用
if __name__ == '__main__':
    #测试文本
    # write_pwd(2048)
    plaintext = "root"
    ciphertext = rsa_encrypt(plaintext)
    print("原文：",plaintext)
    print("加密后：",ciphertext)
    from backend.app.app import rsa_private_key
    # ciphertext = "WCgUJOhz6eJy1K8JEGh97D00wrPLARKriBRIsV8LqmfXF3eQkPRk7DEWESQ0Yb/4nGA1jMpyYH2Ob0j2qZYcrmgDczmb7D+iLkwrHm1Yv7brnpsiXBWaj/5I+7Y0WD1s5dr/EWyt8crhv5QzB/4w5L2+wy9W+q+q/xfuQjEwIIlX1DAQ2f++F7s9clDVflkELEJXOVORv8I2g1OgZ7dWW35agwIXk7s91+RbaM6Jkin9GMixWuwRjFUswKdVeJuAfIU09NZOeM9HrBN67zl+m6/DaiXYx65+DeM5v7ep+uUiEdohAe6e4vwNlfFd/0yp2xUwGGpfrG26WFKM2KraxQ=="
    ciphertext = "d7eURmkOdG7Wx9dLPketUkcUjc8OFRdlhYaYqxAYcfs2SO664lycbA40AzNWobuKJnidAAy298/XNM6KrVlUxNXbkEsfQWEsv/F2joIungVthfd6wAT/7VbSaagVsn9LTo/o8X5BB+Ubxu5S6yZmjBs3boOuyUvIbOYY8IGVvdqSIa2+TWuJZYD0Z0GzY4TZkYOuM4z6JZII6glfJg1iQgxi8hIYdR/EUFx25SW+Ee6NjSe6hNJYauhllJVpTM9Ssh0GfsbWyZ4f6qe7XNMnqvDbGgxEiPvnDSjVbiIL9bbKaApV1AkpwaFvwtueLrrPiLf+/S4QDZ1yBm5YWoO8aQ=="
    a = rsa_decrypt(ciphertext,rsa_private_key)
    print("-----------------------------------------------------------------")
    print("解密后：",a)
